﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using BHair.Report;

namespace BHair.Report
{
    public partial class 顾客来店统计表 : WeifenLuo.WinFormsUI.Docking.DockContent
    {
        public 顾客来店统计表()
        {
            InitializeComponent();
        }
        string constr = ConfigurationManager.ConnectionStrings["BHair.Properties.Settings.BHairDBConnectionString"].ConnectionString;
        private void button1_Click(object sender, EventArgs e)
        {
            Font a = new Font("GB2312", 8);
            dataGridView1.Font = a;
            DataTable dt = new DataTable();
            //创建列
            dt.Columns.Add("日期", typeof(String));
            dt.Columns.Add("天气", typeof(String));
            dt.Columns.Add("温度低", typeof(String));
            dt.Columns.Add("温度高", typeof(String));
            dt.Columns.Add("星期",typeof(String));
            dt.Columns.Add("人数",typeof(String));
            string sql1 = "SELECT [iname] FROM [items] where jc=1";
            SqlConnection conn1 = new SqlConnection(constr);
            conn1.Open();
            SqlCommand comm = new SqlCommand(sql1,conn1);
            SqlDataReader sdr1 = comm.ExecuteReader();
            while (sdr1.Read())
            {
                dt.Columns.Add(sdr1["iname"].ToString(), typeof(String));

            }
            dt.Columns.Add("总次数", typeof(String));
            conn1.Close();

            //dr[0] = "张三";//通过索引赋值

            //查询时间天气
            string sql2 =string.Format( "SELECT [id] ,[日期] ,[天气] ,[温度低],[温度高],[星期] FROM [天气] where 日期>='{0}' and 日期<='{1} 23:59:59'",dateTimePicker1.Text,dateTimePicker2.Text);
            SqlConnection conn2 = new SqlConnection(constr);
            conn2.Open();
            int cs;
            int zcs;
            int zrs;
            SqlCommand comm2 = new SqlCommand(sql2,conn2);
            SqlDataReader sdr2 = comm2.ExecuteReader();
            //查询项目消费次数
            
            while (sdr2.Read())
            {
                string sql5 = "SELECT [iname] FROM [items] where jc=1";
                SqlConnection conn5 = new SqlConnection(constr);
                conn5.Open();
                SqlCommand comm5 = new SqlCommand(sql5, conn5);
                SqlDataReader sdr5 = comm5.ExecuteReader();
                DataRow dr = dt.NewRow();
                dr["日期"] = sdr2["日期"].ToString();
                dr["天气"] = sdr2["天气"].ToString();
                dr["温度低"] = sdr2["温度低"].ToString();
                dr["温度高"] = sdr2["温度高"].ToString();
                dr["星期"] = sdr2["星期"].ToString();

                while (sdr5.Read())
                {
                    // dt.Columns.Add(sdr1["iname"].ToString(), typeof(String));


                    string sql3 = string.Format("SELECT SUM(xfcs) FROM [jcxf] where xmname='{0}' and riqi>=convert(datetime,'{1} 00:00:00',120) and riqi<=convert(datetime,'{2} 23:59:59',120) ", sdr5["iname"].ToString(), sdr2["日期"].ToString(), sdr2["日期"].ToString());
                    SqlConnection conn3 = new SqlConnection(constr);
                    conn3.Open();
                    SqlCommand comm3 = new SqlCommand(sql3,conn3);
                    
                    if (comm3.ExecuteScalar().ToString() != string.Empty)
                    {
                        cs = Int32.Parse(comm3.ExecuteScalar().ToString());
                    }
                    else
                    {
                        cs = 0;
                    }
                    dr[sdr5["iname"].ToString()] = cs;
                    conn3.Close();
                    //查询消费人数
                    string sqlpep = string.Format("SELECT  count(distinct[cardid]) FROM [jcxf] where riqi>=convert(datetime,'{0} 00:00:01',120) and riqi<=convert(datetime,'{1} 23:59:59',120) ", sdr2["日期"].ToString(), sdr2["日期"].ToString());
                    SqlConnection conn20 = new SqlConnection(constr);
                    conn20.Open();
                    SqlCommand comm20 = new SqlCommand(sqlpep,conn20);
                    if (comm20.ExecuteScalar().ToString() != string.Empty)
                    {
                        zrs = Int32.Parse(comm20.ExecuteScalar().ToString());
                    }
                    else
                    {
                        zrs = 0;
                    }
                    dr["人数"] = zrs;
                    conn20.Close();
                    //查询总次数
                    string sql6 = string.Format("SELECT  sum([xfcs])FROM [jcxf] where riqi>=convert(datetime,'{0} 00:00:01',120) and riqi<=convert(datetime,'{1} 23:59:59',120) ", sdr2["日期"].ToString(), sdr2["日期"].ToString());
                    SqlConnection conn6 = new SqlConnection(constr);
                    conn6.Open();
                    SqlCommand comm6 = new SqlCommand(sql6,conn6);
                    if (comm6.ExecuteScalar().ToString() != string.Empty)
                    {
                        zcs = Int32.Parse(comm6.ExecuteScalar().ToString());
                    }
                    else
                    {
                        zcs = 0;
                    }
                    dr["总次数"] = zcs;
                    conn6.Close();
                }
                
                dt.Rows.Add(dr);
                conn5.Close();
            }
            conn2.Close();
            //conn5.Close();

            dataGridView1.DataSource = dt;

        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
        e.RowBounds.Location.Y,
        dataGridView1.RowHeadersWidth - 4,
        e.RowBounds.Height);

            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
            dataGridView1.RowHeadersDefaultCellStyle.Font,
                rectangle,
                dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
                TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "导出Excel文件到";

            saveFileDialog.ShowDialog();

            // 这个一定要加上，要不然，点取消按钮就会提示“索引超出了数组界限”的错误。
            //用saveFileDialog.ShowDialog() == DialogResult.Cancle 不管用，会出现2次存储窗口。
            if (saveFileDialog.FileName == "")
            {

                return;
            }


            Stream myStream;
            myStream = saveFileDialog.OpenFile();
            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
            string str = "";
            try
            {
                //写标题       
                for (int i = 0; i < dataGridView1.ColumnCount; i++)
                {
                    if (i > 0)
                    {
                        str += "\t";
                    }
                    str += dataGridView1.Columns[i].HeaderText;
                }
                sw.WriteLine(str);
                //写内容    
                for (int j = 0; j < dataGridView1.Rows.Count; j++)
                {
                    string tempStr = "";
                    for (int k = 0; k < dataGridView1.Columns.Count; k++)
                    {
                        if (k > 0)
                        {
                            tempStr += "\t";
                        }
                        if (dataGridView1.Rows[j].Cells[k].Value != null)
                        {

                            tempStr += dataGridView1.Rows[j].Cells[k].Value.ToString();
                        }
                        else
                        {
                            tempStr += "";
                        }
                    }
                    sw.WriteLine(tempStr);
                }
                sw.Close();
                myStream.Close();
                MessageBox.Show("导出成功");
            }
            catch (Exception err)
            {
                MessageBox.Show(err.ToString());
            }
            finally
            {
                sw.Close();
                myStream.Close();
            }
        }
    }
}
